iT邦幫忙

2025 iThome 鐵人賽

DAY 18
0
自我挑戰組

C++入門即放棄系列 第 18

[DAY18]沒有錯!就是你!

  • 分享至 

  • xImage
  •  

成員函式是甚麼?

📌 寫在 class 裡的函式,專門用來操作該物件的資料

每個人都有一本冒險者手冊

手冊裡寫著:名字、年齡、喜歡的技能

但是光有資料很無聊

所以還要有功能

#include <iostream>
using namespace std;
class Student 
{
	private:
	    string name;
	    int age;
	public:
	    void set(string n, int a) 
	    {
	        name = n;
	        age = a;
	    }
	    void say() 
	    {
	        cout << name << ",";
	        cout << age << " 歲!" << endl;
	    }
};
int main() 
{
    Student s;
    s.set("小A", 14);
    s.say();
    return 0;
}

this 指標是什麼?

📌 指向目前正在操作的那個物件

小A和小B都有一本手冊

他們都有「自我介紹」這個按鈕

可是如果大家同時按下了按鈕

系統怎麼知道是小A在講,還是小B在講?

這時候,就靠一個隱藏的手電筒

它會照亮正在用手冊的人

#include <iostream>
using namespace std;
class Student 
{
	private:
	    string name;
	    int age;
	public:
	    void set(string name, int age) 
	    {
	        this -> name = name;
	        this -> age = age;
	    }
	    void say() 
	    {
	        cout << this -> name << ",";
	        cout << this -> age << " 歲!" << endl;
	    }
};
int main() 
{
    Student s1, s2;
    s1.set("小A", 12);
    s2.set("小B", 14);
    s1.say();
    s2.say();
    return 0;
}

📌 this 可以想成當下函式放入的變數

結論

📌讓物件能「做事」,不單單只是存放資料

每個物件都有屬於自己的 this 指標

this 指標讓物件知道自己是誰

當有許多個物件同時存在時

this 可以幫助我們區分不同物件的屬性


上一篇
[DAY17]組裝與拆解?
下一篇
[DAY19]不一樣的傳遞!
系列文
C++入門即放棄23
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言